package controller

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
	"wangchunguang_blog/model"
	"wangchunguang_blog/service"
)

// 给订阅者发送邮件信息
func SendMail(c *gin.Context) {
	var (
		err error
		res = gin.H{}
		uid uint64
		sub *model.Subscriber
	)
	defer writeJSON(c, res)
	subject := c.PostForm("subject")
	content := c.PostForm("content")
	userId := c.Query("userId")
	if subject != "" || content != "" || userId != "" {
		res["message"] = "请输入完整的信息"
		return
	}
	uid, err = strconv.ParseUint(userId, 10, 64)
	if err != nil {
		res["message"] = "转换为userid错误"
		return
	}
	sub, err = service.GetSubscriberById(uint(uid))
	if err != nil {
		res["message"] = "获取订阅信息失败"
		return
	}

	err = sendMail(sub.Email, subject, content)
	if err != nil {
		res["message"] = "发送邮件失败"
		return
	}
	res["succeed"] = true

}

// 群发邮件
func SendBatchMail(c *gin.Context) {

	var (
		err    error
		res    = gin.H{}
		subs   []*model.Subscriber
		emails = make([]string, 0)
	)

	defer writeJSON(c, res)
	subject := c.PostForm("subject")
	content := c.PostForm("content")
	if subject == "" || content == "" {
		res["message"] = "error parameter"
		return
	}
	subs, err = service.ListSubscriber(true)
	if err != nil {
		res["message"] = "获取订阅信息失败"
		return
	}
	for _, sub := range subs {
		emails = append(emails, sub.Email)

	}
	err = sendMail(strings.Join(emails, ";"), subject, content)
	if err != nil {
		res["message"] = err.Error()
		return
	}
	res["succeed"] = true
}
